package com.zzhrtech.wgzx_cityzen.ui.me;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.me.MapPointBean;
import com.zzhrtech.wgzx_cityzen.beans.me.MapVideoPointBean;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapPointActivity extends BaseActivity implements OnDateSetListener {

    MapView mMapView;
    AMap aMap;
    private TextView tv_starttime,tv_endtime;


    private TimePickerDialog timePickerDialog;

    private String startTime = "",endTime=  "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_point);
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        toolbar.setNavigationIcon(R.mipmap.ic_close);

        initMap();


        tv_starttime = (TextView) findViewById(R.id.tv_starttime);
        tv_endtime = (TextView) findViewById(R.id.tv_endtime);

        tv_starttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                timePickerDialog.show(getSupportFragmentManager(),"start");
            }
        });

        tv_endtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                timePickerDialog.show(getSupportFragmentManager(),"end");
            }
        });

        timePickerDialog = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId("时间选择")
                .setThemeColor(getResources().getColor(R.color.colorPrimary))
                .setCallBack(this)
                .build();

        httpGetpoint("","");
        httpGetVideopoint();
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();


            setUpMap();
        }
    }

    private void setUpMap(){
        LatLng latLng = new LatLng(43.909295,125.321239);
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latLng, 9, 30, 0));

        aMap.moveCamera(update);

        aMap.setOnMarkerClickListener(listener);
    }

    AMap.OnMarkerClickListener listener = new AMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker arg0) {
            // TODO Auto-generated method stub

            if (arg0.getSnippet().equals("视频")){
                Intent intent = new Intent(MapPointActivity.this,MonitorActivity.class);
                startActivity(intent);
            }

            return false;
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }


    private void httpGetpoint(String startTime,String endTime){
        Map<String,String> params = new HashMap<String, String>();
        params.put("start",startTime);
        params.put("end",endTime);

        GsonRequest<MapPointBean> gsonRequest = new GsonRequest<MapPointBean>(com.android.volley.Request.Method.POST, Constans.HTTP_MAPPOINT, MapPointBean.class, params, new com.android.volley.Response.Listener<MapPointBean>() {
            @Override
            public void onResponse(MapPointBean response) {

                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {

                    aMap.clear(true);
                    Log.d("fail========",response.getMsg());
//                    showToast(tv_time,response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpGetVideopoint(){

        GsonRequest<MapVideoPointBean> gsonRequest = new GsonRequest<MapVideoPointBean>(com.android.volley.Request.Method.POST, Constans.HTTP_MAPVIDEO, MapVideoPointBean.class, null, new com.android.volley.Response.Listener<MapVideoPointBean>() {
            @Override
            public void onResponse(MapVideoPointBean response) {

                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 1;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {

                    Log.d("fail========",response.getMsg());
//                    showToast(tv_time,response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0) {

            List<MapPointBean.Data> data = (List<MapPointBean.Data>) msg.obj;

                Log.d("size===========",data.size() + "");
            for (int i = 0; i < data.size();i++) {

                LatLng latLng = new LatLng(Double.parseDouble(data.get(i).getPoint().get(1)), Double.parseDouble(data.get(i).getPoint().get(0)));
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latLng);

                Bitmap bitmap = null;
                switch (data.get(i).getStatus()) {
                    case "0":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark1);
                        break;
                    case "1":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark2);
                        break;
                    case "2":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark3);
                        break;
                    case "3":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark4);
                        break;
                    case "4":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark5);
                        break;
                    case "5":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark6);
                        break;
                    case "6":
                        bitmap = BitmapFactory.decodeResource(getResources(),
                                R.mipmap.ic_mark7);
                        break;
                }

                markerOptions.title(data.get(i).getCat_name()).snippet(data.get(i).getCi_name() + " - " + data.get(i).getCis_name());

                markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));

                aMap.addMarker(markerOptions);
            }
            }else if (msg.what == 1){
                List<MapVideoPointBean.Data> data = (List<MapVideoPointBean.Data>) msg.obj;
                for (int i = 0; i < data.size();i++) {

                    LatLng latLng = new LatLng(Double.parseDouble(data.get(i).getPoint().get(1)), Double.parseDouble(data.get(i).getPoint().get(0)));
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(latLng);
                    markerOptions.snippet("视频");
                    markerOptions.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),
                            R.mipmap.ic_markersp)));

                    aMap.addMarker(markerOptions);

                }

            }
            return false;
        }
    });

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTag().equals("start")){
            startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date(millseconds));
            tv_starttime.setText(startTime);
        }else {
            endTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date(millseconds));
            tv_endtime.setText(endTime);
            httpGetpoint(startTime,endTime);
        }
    }
}
